<template>
  <div class="warning-records">
    <div class="page-header">
      <h1>管廊系统告警记录</h1>
      <div class="header-actions">
        <t-date-range-picker
          v-model="dateRange"
          :presets="dateRangePresets"
          @change="handleDateRangeChange"
          style="margin-right: 16px"
        />
        <t-select
          v-model="warningType"
          style="width: 150px; margin-right: 16px"
          placeholder="告警类型"
          clearable
          @change="handleFilterChange"
        >
          <t-option value="" label="全部类型" />
          <t-option value="设备预警" label="设备预警" />
          <t-option value="环境预警" label="环境预警" />
          <t-option value="运行预警" label="运行预警" />
          <t-option value="安全预警" label="安全预警" />
          <t-option value="维护提醒" label="维护提醒" />
        </t-select>
        <t-select
          v-model="warningLevel"
          style="width: 150px; margin-right: 16px"
          placeholder="告警等级"
          clearable
          @change="handleFilterChange"
        >
          <t-option value="" label="全部等级" />
          <t-option value="低" label="低" />
          <t-option value="中" label="中" />
          <t-option value="高" label="高" />
        </t-select>
        <t-input
          v-model="searchText"
          placeholder="搜索告警信息"
          style="width: 200px"
          clearable
        >
          <template #suffix-icon>
            <t-icon name="search" @click="handleSearch" />
          </template>
        </t-input>
      </div>
    </div>

    <div class="statistics-cards">
      <t-row :gutter="16">
        <t-col :span="6">
          <t-card title="今日告警" :hover-shadow="true">
            <div class="statistic-value">{{ statistics.today }}</div>
            <div class="statistic-trend" :class="{ 'trend-up': statistics.todayTrend > 0, 'trend-down': statistics.todayTrend < 0 }">
              <t-icon :name="statistics.todayTrend > 0 ? 'arrow-up' : 'arrow-down'" />
              <span>{{ Math.abs(statistics.todayTrend) }}%</span>
              <span class="trend-text">较昨日</span>
            </div>
          </t-card>
        </t-col>
        <t-col :span="6">
          <t-card title="本周告警" :hover-shadow="true">
            <div class="statistic-value">{{ statistics.week }}</div>
            <div class="statistic-trend" :class="{ 'trend-up': statistics.weekTrend > 0, 'trend-down': statistics.weekTrend < 0 }">
              <t-icon :name="statistics.weekTrend > 0 ? 'arrow-up' : 'arrow-down'" />
              <span>{{ Math.abs(statistics.weekTrend) }}%</span>
              <span class="trend-text">较上周</span>
            </div>
          </t-card>
        </t-col>
        <t-col :span="6">
          <t-card title="本月告警" :hover-shadow="true">
            <div class="statistic-value">{{ statistics.month }}</div>
            <div class="statistic-trend" :class="{ 'trend-up': statistics.monthTrend > 0, 'trend-down': statistics.monthTrend < 0 }">
              <t-icon :name="statistics.monthTrend > 0 ? 'arrow-up' : 'arrow-down'" />
              <span>{{ Math.abs(statistics.monthTrend) }}%</span>
              <span class="trend-text">较上月</span>
            </div>
          </t-card>
        </t-col>
        <t-col :span="6">
          <t-card title="告警处理率" :hover-shadow="true">
            <div class="statistic-value">{{ statistics.processRate }}%</div>
            <t-progress :percentage="statistics.processRate" :color="{ from: '#0052D9', to: '#00A870' }" />
          </t-card>
        </t-col>
      </t-row>
    </div>

    <t-tabs v-model="activeTab" :list="tabList" @change="handleTabChange" />

    <t-table
      :columns="columns"
      :data="filteredWarnings"
      :loading="loading"
      :pagination="{ pageSize: 10 }"
      bordered
      row-key="id"
    >
      <template #level="{ row }">
        <t-tag :theme="getWarningLevelTheme(row.level)" variant="light">
          {{ row.level }}
        </t-tag>
      </template>
      <template #status="{ row }">
        <t-tag :theme="row.status === '已确认' ? 'success' : 'warning'" variant="light">
          {{ row.status }}
        </t-tag>
      </template>
      <template #op="{ row }">
        <t-space>
          <t-link theme="primary" hover="color" @click="handleViewDetails(row)">查看详情</t-link>
          <t-link 
            theme="primary" 
            hover="color" 
            @click="handleConfirmWarning(row)" 
            v-if="row.status !== '已确认'"
          >
            确认告警
          </t-link>
          <span v-else>已确认</span>
        </t-space>
      </template>
    </t-table>

    <!-- 告警详情对话框 -->
    <t-dialog
      v-model:visible="detailsVisible"
      header="告警详情"
      :footer="false"
      width="700px"
    >
      <div v-if="currentWarning" class="warning-details">
        <t-descriptions bordered :column="2">
          <t-descriptions-item label="告警ID" :span="1">{{ currentWarning.id }}</t-descriptions-item>
          <t-descriptions-item label="告警时间" :span="1">{{ currentWarning.time }}</t-descriptions-item>
          <t-descriptions-item label="设备名称" :span="1">{{ currentWarning.deviceName }}</t-descriptions-item>
          <t-descriptions-item label="设备位置" :span="1">{{ currentWarning.deviceLocation }}</t-descriptions-item>
          <t-descriptions-item label="告警类型" :span="1">{{ currentWarning.type }}</t-descriptions-item>
          <t-descriptions-item label="告警等级" :span="1">
            <t-tag :theme="getWarningLevelTheme(currentWarning.level)" variant="light">{{ currentWarning.level }}</t-tag>
          </t-descriptions-item>
          <t-descriptions-item label="告警状态" :span="1">
            <t-tag :theme="currentWarning.status === '已确认' ? 'success' : 'warning'" variant="light">{{ currentWarning.status }}</t-tag>
          </t-descriptions-item>
          <t-descriptions-item label="确认人员" :span="1">{{ currentWarning.confirmer || '-' }}</t-descriptions-item>
          <t-descriptions-item label="告警描述" :span="2">{{ currentWarning.description }}</t-descriptions-item>
          <t-descriptions-item label="建议措施" :span="2">{{ currentWarning.suggestion }}</t-descriptions-item>
          <t-descriptions-item label="确认备注" :span="2">{{ currentWarning.confirmNote || '-' }}</t-descriptions-item>
        </t-descriptions>

        <div class="warning-chart" v-if="currentWarning.chartData">
          <h3>告警趋势图</h3>
          <!-- 这里可以添加图表组件，如 ECharts -->
          <div class="chart-placeholder">
            <p>此处可集成图表组件展示告警相关的数据趋势</p>
          </div>
        </div>

        <div class="action-buttons" v-if="currentWarning.status !== '已确认'">
          <t-button theme="primary" @click="handleConfirmCurrentWarning">确认此告警</t-button>
        </div>
      </div>
    </t-dialog>

    <!-- 确认告警对话框 -->
    <t-dialog
      v-model:visible="confirmVisible"
      header="确认告警"
      :confirm-loading="confirmLoading"
      @confirm="confirmWarning"
    >
      <t-form
        ref="confirmFormRef"
        :data="confirmForm"
        :rules="rules"
        :label-width="80"
      >
        <t-form-item label="确认人" name="confirmer">
          <t-input v-model="confirmForm.confirmer" />
        </t-form-item>
        <t-form-item label="确认备注" name="confirmNote">
          <t-textarea v-model="confirmForm.confirmNote" :rows="4" />
        </t-form-item>
      </t-form>
    </t-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { MessagePlugin } from 'tdesign-vue-next';
import dayjs from 'dayjs';

// 表格列定义
const columns = [
  {
    colKey: 'id',
    title: '告警ID',
    width: '80',
  },
  {
    colKey: 'time',
    title: '告警时间',
    width: '180',
    sorter: true,
  },
  {
    colKey: 'deviceName',
    title: '设备名称',
    width: '150',
  },
  {
    colKey: 'type',
    title: '告警类型',
    width: '120',
  },
  {
    colKey: 'level',
    title: '告警等级',
    width: '100',
    cell: 'level',
  },
  {
    colKey: 'description',
    title: '告警描述',
    ellipsis: true,
  },
  {
    colKey: 'status',
    title: '状态',
    width: '100',
    cell: 'status',
  },
  {
    colKey: 'op',
    title: '操作',
    width: '150',
    cell: 'op',
  },
];

// 标签页定义
const tabList = [
  { value: 'all', label: '全部' },
  { value: 'unconfirmed', label: '未确认' },
  { value: 'confirmed', label: '已确认' },
  { value: 'device', label: '设备预警' },
  { value: 'environment', label: '环境预警' },
  { value: 'maintenance', label: '维护提醒' },
];

// 告警统计数据
const statistics = reactive({
  today: 15,
  todayTrend: -5,
  week: 87,
  weekTrend: 12,
  month: 342,
  monthTrend: -3,
  processRate: 85,
});

// 模拟数据
const warnings = ref([
  {
    id: 'W1001',
    time: '2023-09-20 08:23:45',
    deviceName: '气体检测器B',
    deviceLocation: '管廊中段B区',
    type: '环境预警',
    level: '中',
    description: '管廊中段B区气体检测器检测到甲烷浓度接近预警阈值，当前浓度值达到LEL的15%',
    suggestion: '建议加强区域通风，检查管道接口是否存在微小泄漏',
    status: '已确认',
    confirmer: '张工',
    confirmNote: '已安排人员检查管道接口，并增加通风频率',
    chartData: true,
  },
  {
    id: 'W1002',
    time: '2023-09-20 10:35:12',
    deviceName: '温湿度传感器A',
    deviceLocation: '管廊中段A区',
    type: '环境预警',
    level: '低',
    description: '管廊中段A区湿度超过正常范围，当前湿度85%，可能影响设备正常运行',
    suggestion: '建议检查是否存在渗水点，必要时开启除湿设备',
    status: '未确认',
    confirmer: '',
    confirmNote: '',
    chartData: true,
  },
  {
    id: 'W1003',
    time: '2023-09-19 14:12:33',
    deviceName: '控制器A',
    deviceLocation: '管廊控制室',
    type: '设备预警',
    level: '高',
    description: '控制器A运行内存使用率超过90%，可能导致系统响应缓慢或服务中断',
    suggestion: '建议检查控制器运行状态，必要时重启系统或清理缓存',
    status: '已确认',
    confirmer: '李工',
    confirmNote: '已重启控制器，内存使用率恢复正常',
    chartData: true,
  },
  {
    id: 'W1004',
    time: '2023-09-19 16:45:22',
    deviceName: '网关设备',
    deviceLocation: '管廊控制室',
    type: '设备预警',
    level: '中',
    description: '网关设备CPU使用率持续超过80%，网络通信可能受到影响',
    suggestion: '建议检查网关负载，排查是否存在异常连接或数据传输',
    status: '未确认',
    confirmer: '',
    confirmNote: '',
    chartData: true,
  },
  {
    id: 'W1005',
    time: '2023-09-18 09:05:17',
    deviceName: '气体检测器A',
    deviceLocation: '管廊出口',
    type: '维护提醒',
    level: '低',
    description: '气体检测器A已运行180天，接近定期维护周期',
    suggestion: '建议安排定期维护，校准传感器参数',
    status: '未确认',
    confirmer: '',
    confirmNote: '',
    chartData: false,
  },
  {
    id: 'W1006',
    time: '2023-09-18 11:30:45',
    deviceName: '入口摄像头',
    deviceLocation: '管廊入口',
    type: '维护提醒',
    level: '低',
    description: '入口摄像头镜头可能存在污染，图像清晰度下降',
    suggestion: '建议清洁摄像头镜头',
    status: '已确认',
    confirmer: '王工',
    confirmNote: '已安排人员清洁镜头',
    chartData: false,
  },
  {
    id: 'W1007',
    time: '2023-09-17 13:20:18',
    deviceName: '管廊照明系统',
    deviceLocation: '管廊全段',
    type: '运行预警',
    level: '中',
    description: '管廊照明系统部分区域亮度不足，可能存在灯具故障',
    suggestion: '建议检查照明系统，更换损坏灯具',
    status: '已确认',
    confirmer: '赵工',
    confirmNote: '已更换3处损坏灯具',
    chartData: false,
  },
  {
    id: 'W1008',
    time: '2023-09-17 15:40:33',
    deviceName: '安防系统',
    deviceLocation: '管廊出口',
    type: '安全预警',
    level: '高',
    description: '管廊出口安防系统检测到异常访问尝试',
    suggestion: '建议检查门禁系统，查看监控录像确认是否存在安全风险',
    status: '已确认',
    confirmer: '刘工',
    confirmNote: '经检查为维护人员操作不当导致，已重新培训相关人员',
    chartData: false,
  },
]);

// 状态变量
const loading = ref(false);
const searchText = ref('');
const warningType = ref('');
const warningLevel = ref('');
const dateRange = ref([]);
const activeTab = ref('all');
const detailsVisible = ref(false);
const confirmVisible = ref(false);
const confirmLoading = ref(false);
const currentWarning = ref(null);
const confirmFormRef = ref(null);

// 确认表单
const confirmForm = reactive({
  confirmer: '',
  confirmNote: '',
});

// 表单验证规则
const rules = {
  confirmer: [{ required: true, message: '请输入确认人姓名', trigger: 'blur' }],
  confirmNote: [{ required: true, message: '请输入确认备注', trigger: 'blur' }],
};

// 日期范围预设
const dateRangePresets = {
  '今天': [dayjs().startOf('day').toDate(), dayjs().endOf('day').toDate()],
  '本周': [dayjs().startOf('week').toDate(), dayjs().endOf('week').toDate()],
  '本月': [dayjs().startOf('month').toDate(), dayjs().endOf('month').toDate()],
  '最近7天': [dayjs().subtract(7, 'day').toDate(), dayjs().toDate()],
  '最近30天': [dayjs().subtract(30, 'day').toDate(), dayjs().toDate()],
};

// 根据筛选条件过滤告警记录
const filteredWarnings = computed(() => {
  let result = [...warnings.value];
  
  // 按标签页筛选
  if (activeTab.value !== 'all') {
    if (activeTab.value === 'unconfirmed') {
      result = result.filter(warning => warning.status === '未确认');
    } else if (activeTab.value === 'confirmed') {
      result = result.filter(warning => warning.status === '已确认');
    } else if (activeTab.value === 'device') {
      result = result.filter(warning => warning.type === '设备预警');
    } else if (activeTab.value === 'environment') {
      result = result.filter(warning => warning.type === '环境预警');
    } else if (activeTab.value === 'maintenance') {
      result = result.filter(warning => warning.type === '维护提醒');
    }
  }
  
  // 按日期范围筛选
  if (dateRange.value && dateRange.value.length === 2 && dateRange.value[0] && dateRange.value[1]) {
    const startDate = dayjs(dateRange.value[0]).startOf('day');
    const endDate = dayjs(dateRange.value[1]).endOf('day');
    result = result.filter(warning => {
      const warningDate = dayjs(warning.time);
      return warningDate.isAfter(startDate) && warningDate.isBefore(endDate);
    });
  }
  
  // 按告警类型筛选
  if (warningType.value) {
    result = result.filter(warning => warning.type === warningType.value);
  }
  
  // 按告警等级筛选
  if (warningLevel.value) {
    result = result.filter(warning => warning.level === warningLevel.value);
  }
  
  // 按搜索文本筛选
  if (searchText.value) {
    const keyword = searchText.value.toLowerCase();
    result = result.filter(warning => 
      warning.deviceName.toLowerCase().includes(keyword) ||
      warning.description.toLowerCase().includes(keyword) ||
      warning.type.toLowerCase().includes(keyword)
    );
  }
  
  return result;
});

// 获取告警等级对应的主题
const getWarningLevelTheme = (level) => {
  switch (level) {
    case '高': return 'danger';
    case '中': return 'warning';
    case '低': return 'success';
    default: return 'default';
  }
};

// 处理日期范围变化
const handleDateRangeChange = (dates) => {
  // 日期范围变化的处理逻辑已通过计算属性实现
};

// 处理筛选条件变化
const handleFilterChange = () => {
  // 筛选条件变化的处理逻辑已通过计算属性实现
};

// 处理搜索
const handleSearch = () => {
  // 搜索逻辑已通过计算属性实现
};

// 处理标签页切换
const handleTabChange = (value) => {
  activeTab.value = value;
};

// 查看告警详情
const handleViewDetails = (row) => {
  currentWarning.value = { ...row };
  detailsVisible.value = true;
};

// 确认告警
const handleConfirmWarning = (row) => {
  currentWarning.value = { ...row };
  confirmForm.confirmer = '';
  confirmForm.confirmNote = '';
  confirmVisible.value = true;
};

// 确认当前告警
const handleConfirmCurrentWarning = () => {
  detailsVisible.value = false;
  handleConfirmWarning(currentWarning.value);
};

// 确认告警提交
const confirmWarning = () => {
  confirmFormRef.value.validate().then((result) => {
    if (result === true) {
      confirmLoading.value = true;
      
      setTimeout(() => {
        // 更新告警状态
        const index = warnings.value.findIndex(item => item.id === currentWarning.value.id);
        if (index !== -1) {
          warnings.value[index] = {
            ...warnings.value[index],
            status: '已确认',
            confirmer: confirmForm.confirmer,
            confirmNote: confirmForm.confirmNote,
          };
          
          // 更新当前告警对象（用于详情显示）
          currentWarning.value = {
            ...currentWarning.value,
            status: '已确认',
            confirmer: confirmForm.confirmer,
            confirmNote: confirmForm.confirmNote,
          };
          
          MessagePlugin.success('告警确认成功');
        }
        
        confirmVisible.value = false;
        confirmLoading.value = false;
      }, 500);
    }
  }).catch(error => {
    console.log('验证失败:', error);
  });
};

// 生命周期钩子
onMounted(() => {
  // 这里可以添加从API获取告警记录的逻辑
  loading.value = true;
  setTimeout(() => {
    loading.value = false;
  }, 500);
});
</script>

<style scoped>
.warning-records {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.header-actions {
  margin-top: 16px;
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.statistics-cards {
  margin-bottom: 24px;
}

.statistic-value {
  font-size: 24px;
  font-weight: 600;
  margin-bottom: 8px;
}

.statistic-trend {
  display: flex;
  align-items: center;
  font-size: 14px;
  gap: 4px;
}

.trend-up {
  color: #e34d59;
}

.trend-down {
  color: #00a870;
}

.trend-text {
  color: #999;
  margin-left: 4px;
}

.warning-details {
  margin-bottom: 20px;
}

.warning-chart {
  margin-top: 24px;
}

.chart-placeholder {
  height: 200px;
  background-color: #f5f5f5;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 4px;
}

.action-buttons {
  margin-top: 24px;
  text-align: right;
}
</style> 